<?php
/**
 * Created by PhpStorm.
 * User: lifeilin
 * Date: 2017/6/22 0022
 * Time: 10:40
 */

namespace Cuke\Library\Paginator;

use Phalcon\Paginator\AdapterInterface as PaginatorInterface;

/**
 * 分页组件
 *
 * 使用方法：
 *     $paginator = new PaginatorArray([
 *       'data'          => $coupon_list['lists'],
 *       'limit'         => 15,
 *       'current'       => $page_index,
 *       'total_items'   => $coupon_list['total_count'],
 *       'href'          => '/coupon/list',
 *       'params'        => [ 'coupon_name' => $coupon_name, 'coupon_state' => $coupon_state]
 *     ]);
 * @package BaiyangDaojia\Library\Paginator
 */
class PaginatorArray implements  PaginatorInterface
{
    /**
     * @var array 数据列表
     */
    public $items = [];
    /**
     * @var int 当前页码
     */
    public $current = 1;
    /**
     * @var int 总记录条数
     */
    public $total_items = 0;
    /**
     * @var int 总页数
     */
    public $total_pages  = 0;  //总页数
    public $last;

    protected $page;
    protected $showPages    = 5;   //需要显示的页数
    protected $subPages     = 15;    //每页显示条数
    protected $href         = '';        //连接
    protected $page_arr     = array();    //保存生成的页码 键页码 值为连接
    protected $params       = [];

    public function __construct(array $config)
    {
        if(isset($config['total_items'])){
            $this->total_items = intval($config['total_items']);
        }else{
            throw new \Exception('总页数不能为空');
        }
        if(isset($config['show_pages'])){
            $this->showPages = intval($config['show_pages']);
        }
        if(isset($config['current'])){
            $this->current = intval($config['current']);
        }
        if(isset($config['limit'])){
            $this->subPages = intval($config['limit']);
        }
        if(isset($config['href'])){
            $this->href = $config['href'];
        }else{
            $this->href = htmlentities($_SERVER['PHP_SELF']);
        }

        if(isset($config['data'])){
            $this->items = $config['data'];
        }

        if(isset($config['params'])){
            $this->params = $config['params'];
        }
        
        $this->constructPages();
    }

    /**
     * Set the current page number
     *
     * @param int $page
     */
    public function setCurrentPage($page)
    {
        $this->current = intval($page);
    }

    /**
     * Returns a slice of the resultset to show in the pagination
     *
     * @return \stdClass
     */
    public function getPaginate()
    {
        return $this->createPaginator();
    }

    /**
     * Set current rows limit
     *
     * @param int $limit
     */
    public function setLimit($limit)
    {
        $this->subPages = $limit;
    }

    /**
     * Get current rows limit
     *
     * @return int
     */
    public function getLimit()
    {
        return $this->subPages;
    }

    protected function createPaginator()
    {
        /* 构造普通模式的分页
            共4523条记录,每页显示10条,当前第1/453页 [首页] [上页] [1] [2] [3] .. [下页] [尾页]
        */
        $pageStr = '<div class="pull-left">共 ' . $this->total_items. ' 条记录，每页显示 ' . $this->subPages . ' 条';
        $pageStr .= '当前第 ' . $this->current . '/' . $this->total_pages . ' 页 </div><div class="pull-right"><ul>';

        $this->params['page'] = 1;
        if($this->current == 1){
            $pageStr .= '<li><a href="javascript:;">首页</a> </li>';

        }else{
            $pageStr .= '<li><a href="' . $this->href . '?' . http_build_query($this->params) . '">首页</a> </li>';
        }

        //如果当前页不是第一页就显示上页
//        if ($this->current > 1) {
//            $this->params['page'] = $this->current - 1;
//            $pageStr .= '<li><a href="' . $this->href . '?' . http_build_query($this->params) . '">上页</a> </li>';
//        }

        foreach ($this->page_arr as $k => $v) {
            $this->params['page'] = $k;
            if($this->current == $k){
                $pageStr .= '<li class="active"><a>' . $k . '</a> </li>';
            }else{
                $pageStr .= '<li><a href="' . $v . '">' . $k . '</a> </li>';
            }
        }

        //如果当前页小于总页数就显示下一页
//        if ($this->current < $this->total_pages) {
//            $this->params['page'] = $this->current + 1;
//            $pageStr .= '<li><a href="' . $this->href . '?' . http_build_query($this->params) . '">下页</a> </li>';
//        }

        $this->params['page'] = $this->total_pages;
        if($this->current == $this->total_pages || $this->total_pages == 0){
            $pageStr .= '<li><a title="尾页">尾页</a> </li>';
        }else{
            $pageStr .= '<li><a href="' . $this->href . '?' . http_build_query($this->params) . '">尾页</a> </li>';

        }

        return $pageStr . '</ul></div>';
    }

    /**
     * construct_Pages 生成页码数组
     * 键为页码，值为链接
     * $this->page_arr=Array(
     *                  [1] => index.php?page=1
     *                  [2] => index.php?page=2
     *                  [3] => index.php?page=3
     *                  ......)
     */
    protected function constructPages()
    {
        //计算总页数
        $this->total_pages = ceil($this->total_items / $this->subPages);
        $this->last = $this->total_pages;
        //根据当前页计算前后页数
        $leftPage_num = floor($this->showPages / 2);
        $rightPage_num = $this->showPages - $leftPage_num;

        //左边显示数为当前页减左边该显示的数 例如总显示7页 当前页是5  左边最小为5-3  右边为5+3
        $left = $this->current - $leftPage_num;
        $left = max($left, 1); //左边最小不能小于1
        $right = $left + $this->showPages - 1; //左边加显示页数减1就是右边显示数
        $right = min($right, $this->total_pages);  //右边最大不能大于总页数
        $left = max($right - $this->showPages + 1, 1); //确定右边再计算左边，必须二次计算

        for ($i = $left; $i <= $right; $i++) {
            $this->params['page'] = $i;
            $this->page_arr[$i] = $this->href . '?' . http_build_query($this->params);
        }
    }
}